using System.Collections;
using UnityEngine;

public class EnemyHealth : MonoBehaviour
{
    public int maxHealth = 100;
    public int currentHealth;
    // public ParticleSystem m_smokeDead;
    public ParticleSystem m_tankExplosion;
    public AudioSource m_AudioSource;
    public AudioClip soundFire;
    private Animator animator;

    private Renderer[] renderers;
    private Material[][] originalMaterials;

    public Material flashWhiteMaterial; // 拖入纯白材质

    [Header("掉落设置")]
    [Range(0f, 1f)]
    public float dropProbability = 0.33f;      // 掉落概率（0.33即33%）
    public GameObject dropPrefabs;           // 掉落物预制体数组

    void OnEnable()
    {
        currentHealth = maxHealth;
        animator = GetComponentInChildren<Animator>();

        // 获取“第一个子对象”下的所有子孙 Renderer
        if (transform.childCount > 0)
        {
            Transform firstChild = transform.GetChild(0);
            renderers = firstChild.GetComponentsInChildren<Renderer>(true);
            originalMaterials = new Material[renderers.Length][];

            for (int i = 0; i < renderers.Length; i++)
            {
                originalMaterials[i] = renderers[i].materials;
            }
        }
        else
        {
            renderers = new Renderer[0];
        }
    }

    void OnTriggerEnter(Collider col)
    {
        if (col.gameObject.name == "friendlyShell")
        {
            SCT_Shell shell = col.GetComponent<SCT_Shell>();
            if (shell != null)
            {
                Damage(shell.shellDamage);
            }
        }
    }

    public void Damage(int damageAmount)
    {
        currentHealth -= damageAmount;

        StartCoroutine(FlashAddMaterial());

        if (currentHealth <= 0)
        {
            GetComponent<EnemyTankFollower>().enabled = false;
            animator.enabled = true;
            animator.SetBool("Dead" + Random.Range(1, 5), true);

            m_AudioSource.loop = false;
            m_AudioSource.pitch = 1;
            m_AudioSource.clip = null;
            m_AudioSource.PlayOneShot(soundFire);

            GetComponent<BoxCollider>().enabled = false;
            gameObject.tag = "Respawn";

            // m_smokeDead.Play();
            m_tankExplosion.Play();
            m_tankExplosion.gameObject.GetComponent<AudioSource>().Play();

            // 获取父对象上的 EnemyTankManager 脚本
            EnemyTankManager manager = GetComponentInParent<EnemyTankManager>();
            bool shouldDrop = false;

            if (manager != null)
            {
                manager.num += 1;

                if (manager.num >= 5)
                {
                    shouldDrop = true;
                    manager.num = 0;
                }
                else
                {
                    shouldDrop = Random.value < dropProbability;
                }
            }
            else
            {
                // 没找到 manager，则按默认概率
                shouldDrop = Random.value < dropProbability;
            }
            transform.parent.GetComponent<EnemyTankManager>().enemydies++;

            if (transform.parent.GetComponent<EnemyTankManager>().enemydies == 1 || transform.parent.GetComponent<EnemyTankManager>().enemydies == 3)
            {
                GameObject dropInstance1 = Instantiate(dropPrefabs);
                dropInstance1.transform.position = new Vector3(0, 0f, transform.position.z);
                dropInstance1.transform.rotation = Quaternion.identity;
                dropInstance1.SetActive(true);
                GameObject dropInstance2 = Instantiate(dropPrefabs);
                dropInstance2.transform.position = new Vector3(-6, 0f, transform.position.z);
                dropInstance2.transform.rotation = Quaternion.identity;
                dropInstance2.SetActive(true);
                GameObject dropInstance3 = Instantiate(dropPrefabs);
                dropInstance3.transform.position = new Vector3(6, 0f, transform.position.z);
                dropInstance3.transform.rotation = Quaternion.identity;
                dropInstance3.SetActive(true);
            }

            // 掉落道具
            if (dropPrefabs != null && shouldDrop)
            {
                GameObject drop = dropPrefabs;
                if (drop != null)
                {
                    GameObject dropInstance = Instantiate(drop);
                    dropInstance.transform.position = new Vector3(transform.position.x, 0f, transform.position.z);
                    dropInstance.transform.rotation = Quaternion.identity;
                    dropInstance.SetActive(true);
                }
            }

            StartCoroutine(hideTank());

            Rigidbody rb = GetComponent<Rigidbody>();
            if (rb != null)
            {
                rb.useGravity = true;  // 启用重力
            }
        }
    }

    private IEnumerator FlashAddMaterial()
    {
        for (int i = 0; i < renderers.Length; i++)
        {
            Material[] newMats = new Material[originalMaterials[i].Length + 1];
            originalMaterials[i].CopyTo(newMats, 0);
            newMats[newMats.Length - 1] = flashWhiteMaterial;
            renderers[i].materials = newMats;
        }

        yield return new WaitForSeconds(0.1f);

        for (int i = 0; i < renderers.Length; i++)
        {
            renderers[i].materials = originalMaterials[i];
        }
    }

    private IEnumerator hideTank()
    {
        yield return new WaitForSeconds(1f);
        gameObject.SetActive(false);
        // 通知管理器检查全局状态
        EnemyTankManager manager = transform.parent.GetComponent<EnemyTankManager>();
        if (manager != null)
        {
            manager.CheckAllEnemiesDead(); // 触发检查
        }
    }
}
